package com.oracle.application.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.oracle.application.entity.Address;
import com.oracle.application.entity.Member;
import com.oracle.application.entity.vo.MemberVo;
import com.oracle.application.mapper.AddressMapper;
import com.oracle.application.mapper.MemberMapper;
import com.oracle.application.service.IMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oracle.application.vo.R;
import lombok.Data;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author The Bug Maker
 * @since 2021-07-08
 */
@Service
@Data
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements IMemberService {

    @Autowired(required = false)
    private MemberMapper memberMapper;

    @Autowired(required = false)
    private AddressMapper addressMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public int verifyEmail(String email,boolean flag) {
        QueryWrapper<Member> wrapper=new QueryWrapper<>();
        wrapper.eq("email",email);
        int count=memberMapper.selectCount(wrapper);
        if (count==0 && flag){
            amqpTemplate.convertAndSend("emailExchange", "send.email", email);
        }
        return count;
    }

    @Override
    public R registerMember(MemberVo memberVo) {
        R resultR=new R();
        if (verifyEmail(memberVo.getEmail(),false)>0){
            resultR.setCode(201);
            resultR.setMsg("邮箱已被注册！");
            return resultR;
        }
        String redisCode = redisTemplate.boundValueOps("member:register:" + memberVo.getEmail()).get();
        if (redisCode == null){
            resultR.setCode(201);
            resultR.setMsg("验证码已过期，请重新发送！");
            return resultR;
        }
        Member member = new Member();
        BeanUtils.copyProperties(memberVo, member);
        member.setCreatedate(LocalDateTime.now());
        member.setModifydate(LocalDateTime.now());
        member.setFailcount(0);
        member.setStatus(1);
        memberMapper.insert(member);
        Address address = new Address();
        address.setLocation(memberVo.getLocation());
        address.setPhone(memberVo.getPhone());
        address.setMid(member.getId());
        addressMapper.insert(address);
        resultR.setCode(200);
        resultR.setMsg("ok");
        return resultR;
    }


}
